package com.mrt.chatgpt.data.trigger.http;

import com.mrt.chatgpt.data.types.sdk.weixin.XmlUtil;
import com.mrt.chatgpt.data.domain.weixin.model.entity.MessageTextEntity;
import com.mrt.chatgpt.data.domain.weixin.model.entity.UserBehaviorMessageEntity;
import com.mrt.chatgpt.data.domain.weixin.service.IWeiXinBehaviorService;
import com.mrt.chatgpt.data.domain.weixin.service.IWeiXinValidateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author 86135
 * @Date 2024/3/16 11:19
 * @Description
 * @Version 1.0
 * @快捷键 getterANDsetter ALT+Insert
 * @快捷键 Ctrl+/或者Ctrl+Shift+/都可以快速注释
 * @快捷键 Ctrl+D 快速复制代码
 * @“ctrl+r”快捷键,用于当前文件内容替换,指的是在当前打开的文件中替换匹配的字符,只操作一个文件;
 * @ALT+鼠标左键 整列编辑
 * @快捷键提示 ALT+Enter
 * @快捷键 快速写注释：在方法函数上方输入/** 然后回车
 * @快捷键 Ctrl+O，选择重写的方法
 * @快捷键 ALT+INSERT
 */
@Slf4j
@RestController
//${app.config.api-version} 是一个占位符，会被配置文件中的具体数值替换
@RequestMapping("/wx/portal/{appid}")
public class WeiXinPortalController {
    @Value("${wx.config.originalid}")
    private String originalId;

    @Resource
    private IWeiXinValidateService weiXinValidateService;

    @Resource
    private IWeiXinBehaviorService weiXinBehaviorService;

    /**
     * 处理微信服务器发来的get请求
     * appid     微信端AppID
     * signature 微信端发来的签名
     * timestamp 微信端发来的时间戳
     * nonce     微信端发来的随机字符串
     * echostr   微信端发来的验证字符串
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String vaildate(@PathVariable String appid,
                           @RequestParam(value = "signature", required = false )String signature,
                           @RequestParam(value = "timestamp", required = false)String timestamp,
                           @RequestParam(value = "nonce", required = false)String nonce,
                           @RequestParam(value = "echostr",required = false)String echostr){
        try{
            log.info("微信公众号验签信息{}开始[{}, {}, {}, {}]",appid, signature, timestamp, nonce, echostr);
            if(StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)){
                throw new IllegalAccessException("请求参数非法，请核实!");
            }
            boolean check = weiXinValidateService.checkSign(signature,timestamp,nonce);
            log.info("微信公众号验签{}完成 check：{}", appid, check);
            if (!check) {
                return null;
            }
            return echostr;
        } catch (Exception e) {
            log.error("微信公众号验签信息{}失败 [{}, {}, {}, {}]", appid, signature, timestamp, nonce, echostr, e);
            return null;
        }
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature){
        try{
            log.info("接收微信挂着卖信息请求{}开始{}", openid, requestBody);
            //消息转换
            MessageTextEntity message = XmlUtil.xmlToBean(requestBody, MessageTextEntity.class);
            //构建实体
            UserBehaviorMessageEntity entity = UserBehaviorMessageEntity.builder()
                    .openId(openid)
                    .fromUserName(message.getFromUserName())
                    .msgType(message.getMsgType())
                    .content(StringUtils.isBlank(message.getContent()) ? null : message.getContent().trim())
                    .event(message.getEvent())
                    .createTime(new Date(Long.parseLong(message.getCreateTime()) * 1000L))
                    .build();
            //受理信息
            String result = weiXinBehaviorService.acceptUserBehavior(entity);
            log.info("接收微信公众号信息请求{}完成{}",openid, result);
            return  result;
        }catch (Exception e){
            log.error("接收微信公众号信息请求{}失败 {}",openid, requestBody,e);
            return "";
        }
    }

}
